﻿using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;

namespace iTool.Utils
{
    public class iJwtSecurity
    {
        readonly SymmetricSecurityKey symmetricSecurity;

        /// <summary>
        /// 最少16位
        /// </summary>
        /// <param name="security"></param>
        public iJwtSecurity(string security = "help-itool@qq.com")
        {
            var securityBytes = Encoding.UTF8.GetBytes(security);
            this.symmetricSecurity = new SymmetricSecurityKey(securityBytes);
        }

        public string BuildToken(Claim[] claims)
        {
            //new Claim(ClaimTypes.Name, "ylc"),
            //new Claim(JwtRegisteredClaimNames.Email, "1234567@11.com"),
            //new Claim(JwtRegisteredClaimNames.Sub, "Sub")

            SigningCredentials signingCredentials = new SigningCredentials(symmetricSecurity, SecurityAlgorithms.HmacSha256);

            JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(claims: claims, signingCredentials: signingCredentials);

            JwtSecurityTokenHandler jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
            return jwtSecurityTokenHandler.WriteToken(jwtSecurityToken);
        }

        public string BuildToken(string channel)
        {
            return this.BuildToken(new Claim[] { new Claim("key", channel) });
        }

        public ClaimsPrincipal GetClaims(string token)
        {
            try
            {
                var handler = new JwtSecurityTokenHandler();
                handler.InboundClaimTypeMap.Clear();
                return handler.ValidateToken(token, this.GetTokenValidationParameters(), out _);
            }
            catch
            {
                return null;
            }
        }

        public string GetChannel(ClaimsPrincipal claimsPrincipal)
        {
            try
            {
                if (claimsPrincipal == null)
                {
                    return string.Empty;
                }
                else
                {
                    return (from item in claimsPrincipal.Claims where item.Type == "key" select item.Value).FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                _ = ex;
                return string.Empty;
            }
        }


        public TokenValidationParameters GetTokenValidationParameters()
        {
            return new TokenValidationParameters
            {

                ValidateAudience = false,
                ValidateIssuer = false,
                ValidateIssuerSigningKey = true,
                RequireExpirationTime = false,
                IssuerSigningKey = this.symmetricSecurity
            };
        }




        void StartUp()
        {
            //public void ConfigureServices(IServiceCollection services)

            //var jwt = new iToolJWT();
            // 注入服务  1.开启Bearer认证 2.注册Bearer服务
            // Microsoft.AspNetCore.Authentication.JwtBearer
            //services
            //    .AddAuthentication("Bearer")
            //    .AddJwtBearer(o => o.TokenValidationParameters = jwt.GetTokenValidationParameters());


            // public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            // app.UseAuthentication();


            ///获取Token的三种方式

            //第二种 通过User对象获取
            // var sub = User.FindFirst(d => d.Type == ClaimTypes.Name)?.Value;

            //第三种 通过Httpcontext上下文中直接获取
            //var name = HttpContext.User.Identity.Name;
            //var Claims = HttpContext.User.Claims;
            //var claimstype = (from item in Claims where item.Type == JwtRegisteredClaimNames.Email select item.Value).ToList();

        }
    }
}
